package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Controller
public class FileUpload {
    @RequestMapping("/")
    public String upload()
    {
        return "upload";
    }

    @GetMapping("/result")
    public String result()
    {
        return "result";
    }

    @PostMapping("/upload")
    public String SingleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes)
    {
        if(file.isEmpty())
        {
            redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
            return "redirect:result";
        }
        try
        {
            byte[] bytes = file.getBytes();
            Path path = Paths.get("D:/Users/lenovo/Desktop/111/" + file.getOriginalFilename());
            Files.write(path, bytes);
            redirectAttributes.addFlashAttribute("message",
                    "You successfully uploaded '" + file.getOriginalFilename() + "'");

        }catch (IOException e)
        {
            e.printStackTrace();
        }

        return "redirect:result";
    }
}
